//xhr对象兼容
function createRequest() {
    return new XMLHttpRequest()||new ActiveXObject('Msxml2.XMLHTTP')||new ActiveXObject('Microsoft.XMLHTTP')||null;
}
//针对get请求对象序列化为字符串
/*
* {parma1：val1,
* parma2：val2
* }
*
* parama1=val1&parama2=val2
* */
function serialize(parmas){
    var parmasStr = '';
    if(Object.keys){
        Object.keys(parmas).forEach(function(value){
            parmasStr += (value + '=' + parmas[value]) + '&';
        })
    }else {
        for (var prop in parmas){
            parmasStr += prop + '=' + parmas[prop] + '&';
        }
    }
    return parmasStr.slice(0,-1) ;
}

function ajax(config) {
    var xhr = createRequest()|| console.error('xhr对象创建失败') ;
    (config.method.toLowerCase()==='get'&&config.data)&&(config.url += "?"+serialize(config.data));
    xhr.open(config.method, config.url, config.async) ;
    xhr.onreadystatechange = function(){
        if(xhr.readyState === 4){
            if(xhr.status === 200){
                var res = xhr.responseText;
                if(config.dataType==='json'){
                    res = JSON.parse(res);
                }
                config.success.call(xhr,res);
            }else{
                config.fail.call(xhr,'server error');
            }
        }else{
          config.fail.call(xhr,'server error');
      }
    };
    if(config.data&&config.method.toLowerCase() === 'post'){
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
        xhr.send(serialize(config.data));
    }else{
        xhr.send(null)
    }
}



